module PNEngine
  class Case < ActiveRecord::Base
    include Resource::InstanceMethods
    extend Resource::ClassMethods    
    
    has_many :tokens
    has_one :execution_log
    has_one :execution_context
    
    # Case can be parent of other cases
    belongs_to :parent, :class_name => "PNEngine::Case"
    has_many :children, :class_name => "PNEngine::Case"
    
    after_create :set_log_and_context
     
    def set_log_and_context
      if execution_log.nil?
        self.execution_log = PNEngine::ExecutionLog.new
      end
      if execution_context.nil?
        self.execution_context = PNEngine::ExecutionContext.new
      end
    end
    
    # creates context and datatokens for current case created from petrinet
    def fillWithStandardTokens(pnetid)
      # initialize dataplaces
      dataplaces = Place.find(:all, :conditions => ["contenttype = 'data' AND petrinet_id = ?", pnetid])
      dataplaces.each do |dataplace|
        push_token = PNEngine::Token.new({:value => dataplace.modelxml}, self)
        dataplace.push(push_token)
      end
      # initialize contextplaces
      modelfilename = "public/examples/contextPlace/model_contextplace.xml"
      contextmodel = ""
      file = File.open(modelfilename , "r")
      file.each_line do |line|
        contextmodel << line
      end
      file.close
      contextplaces = Place.find(:all, :conditions => ["contenttype = 'context' AND petrinet_id = ?", pnetid])
      contextplaces.each do |contextplace|
        # contextmodelxml = PARSE...
        # newmodel = childnote.setValue
        # contextmodel = newmodel
        push_token = PNEngine::Token.new({:value => contextmodel}, self)
        contextplace.push(push_token)
      end
    end
  end
end
